
// ========================================================
// FACTORIAL USING FUNCTION CALLS
//
// Calculates: 5! = 5 × 4 × 3 × 2 × 1
//
// x5  = factorial result
// x6  = current multiplier
// x10 = first function argument
// x11 = second function argument
// x12 = function result
// x13 = multiplication counter
// x1  = return address
// ========================================================


start:
        addi  x5, x0, 1          // Result starts at 1
        addi  x6, x0, 5          // Calculate factorial of 5

FactorialLoop:
        beq   x6, x0, Finished   // Stop when multiplier reaches zero

        add   x10, x5, x0        // Argument 1 = current result
        add   x11, x6, x0        // Argument 2 = multiplier

        jal   x1, Multiply       // Call multiplication function

        add   x5, x12, x0        // Copy returned result into x5
        addi  x6, x6, -1         // Move to next multiplier

        jal   x0, FactorialLoop  // Repeat factorial loop

Finished:
        cout  << "Factorial of 5 = " << x5 << endl
        jal   x0, EndProgram


// --------------------------------------------------------
// Multiply function
//
// Input:
//   x10 = first number
//   x11 = second number
//
// Output:
//   x12 = product
// --------------------------------------------------------

Multiply:
        addi  x12, x0, 0         // Product starts at zero
        add   x13, x11, x0       // Counter = second argument

MultiplyLoop:
        beq   x13, x0, Return     // Finished when counter is zero

        add   x12, x12, x10      // Product += first argument
        addi  x13, x13, -1       // Decrease counter

        jal   x0, MultiplyLoop    // Continue multiplication

Return:
        jalr  x0, 0(x1)          // Return to instruction after JAL

EndProgram:
